from django import template
from django.db import models
import re
Post = models.get_model('blog', 'post')
Category = models.get_model('blog', 'category')

register = template.Library()

class LatestPosts(template.Node):
  def __init__(self, format_string, var_name):
    self.format_string = format_string
    self.var_name = var_name
  
  def render(self, context):
    posts = Post.public.all()[:int(self.format_string)]
    context[self.var_name] = posts
    return ''

@register.tag(name='get_latest_posts')
def do_get_latest_posts(parser, token):
  """
  {% get_latest_posts 5 as latest_posts %}
  """
  try:
    tag_name, arg = token.contents.split(None, 1)
  except ValueError:
    raise template.TemplateSyntaxError, "%s tag requires arguments" % token.contents.split()[0]
  m = re.search(r'(.*?) as (\w+)', arg)
  if not m:
    raise template.TemplateSyntaxError, "%s tag had invalid arguments" % tag_name
  format_string, var_name = m.groups()
  return LatestPosts(format_string[0], var_name)


class BlogCategories(template.Node):
  def __init__(self, var_name):
    self.var_name = var_name
  
  def render(self, context):
    categories = Category.objects.all()
    context[self.var_name] = categories
    return ''

@register.tag(name='get_blog_categories')
def do_get_blog_categories(parser, token):
  """
  {% get_blog_categories as category_list %}
  """
  try:
    tag_name, arg = token.contents.split(None, 1)
  except ValueError:
    raise template.TemplateSyntaxError, "%s tag requires arguments" % token.contents.split()[0]
  m = re.search(r'as (\w+)', arg)
  if not m:
    raise template.TemplateSyntaxError, "%s tag had invalid arguments" % tag_name
  var_name = m.groups()[0]
  return BlogCategories(var_name)